package com.open.party.cloud.view.login

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppEventBusTitleBaseActivity
import cn.android.x.utils.ImmSolftManager
import com.open.party.cloud.R
import com.open.party.cloud.model.UserVo
import com.open.party.cloud.viewModel.BaseViewModel
import com.sinothk.android.utils.XUtils
import kotlinx.android.synthetic.main.activity_register2.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 注册信息提交界面
 */
class Register2Activity : AppEventBusTitleBaseActivity() {

    private var viewModel: BaseViewModel? = null

    override fun getLayoutResId(): Int = R.layout.activity_register2

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setViewTitle("注册新用户")

        viewModel = BaseViewModel()

        initView()
        initListener()
    }

    private fun initView() {
        nameEt.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val finalStr = nameEt.text.toString()

                val str = stringFilterChinese(finalStr)

                if (finalStr != str) {
                    nameEt.setText(str)
                    nameEt.setSelection(str!!.length)
                }
            }
        })
    }

    private fun initListener() {
        toRegisterBtn.setOnClickListener {
            ImmSolftManager(this).showKeyboard(false)
            toRegister()
        }

        phoneCodeBtn.setOnClickListener {
            getVercode()
        }
    }

    private fun toRegister() {

        val userVo = UserVo()
        // 名称
        val nameStr = nameEt.text.toString()
        if (XUtils.string().isEmpty(nameStr)) {
            XUtils.toast().show("请输入用户名")
            return
        } else {

        }

        // 手机号
        val phoneStr = accountEt.text.toString()
        if (XUtils.string().isEmpty(phoneStr)) {
            XUtils.toast().show("请输入手机号码")
            return
        }

        if (phoneStr.length != 11 || '1' != phoneStr[0]) {
            XUtils.toast().show("手机号码可能有误")
            return
        }

        val phoneCodeStr = phoneCodeEt.text.toString()
        if (XUtils.string().isEmpty(phoneCodeStr)) {
            XUtils.toast().show("请输入手机验证码")
            return
        }

        // 密码
        val passWordStr = pwdEt.text.toString()
        if (passWordStr.length < 6 || passWordStr.length > 12) {
            XUtils.toast().show("密码长度应在6至12个字符")
            return
        }

        val passWord2Str = pwd2Et.text.toString()
        when {
            XUtils.string().isEmpty(passWordStr) -> {
                XUtils.toast().show("请输入密码")
                return
            }
            XUtils.string().isEmpty(passWord2Str) -> {
                XUtils.toast().show("再次输入密码有误")
                return
            }
            passWordStr != passWord2Str -> {
                XUtils.toast().show("两次输入的密码不一致")
                return
            }
            else -> {
                // XUtils.codeByMd5().stringToMD5(passWordStr)
            }
        }

        userVo.name = nameStr
        userVo.phone = phoneStr
        userVo.password = passWordStr
        userVo.code = phoneCodeStr

        showLoadingDialog("正在注册")
        viewModel!!.doRegister(userVo)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<String>) {

        if ("doRegister" != result.eventType) {
            return
        }

        hideLoadingDialog()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                XUtils.toast().show("注册成功")
                finish()
            }
            ResultInfo.TOKEN_OVERDUE -> {
                // 不存在
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }

    private fun getVercode() {


        if (!XUtils.net().isAvailable) {
            XUtils.toast().show("当前网络不可用")
            return
        }

        // 手机号
        val phoneStr = accountEt.text.toString()
        if (XUtils.string().isEmpty(phoneStr)) {
            XUtils.toast().show("请输入手机号码")
            return
        }

        if (phoneStr.length != 11 || '1' != phoneStr[0]) { //!XUtils.regex().checkMobile(phoneStr)
            XUtils.toast().show("手机号码格式不正确")
            return
        }

        phoneCodeBtn.isEnabled = false

        showLoadingDialog("正在获取验证码")
        viewModel!!.getPhoneCode(phoneStr, "zc")
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun receiveStudentEventBus(msg: String) {
        hideLoadingDialog()
        if (XUtils.string().isEmpty(msg)) {
            XUtils.toast().show(" 信息已发送，请注意查收")
            timer.start()
        } else {
            XUtils.toast().show(msg)
            phoneCodeBtn.isEnabled = true
        }
    }

    @SuppressLint("SetTextI18n")
    var timer: CountDownTimer = object : CountDownTimer(60000, 1000) {

        override fun onTick(millisUntilFinished: Long) {
            phoneCodeBtn.text = "重新发送(${millisUntilFinished / 1000}s)"
        }

        override fun onFinish() {
            phoneCodeBtn.text = "获取验证码"
            phoneCodeBtn.isEnabled = true
        }
    }
}